package com.ly.feishu.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ly.feishu.config.FeishuConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 飞书 token
 *
 * @author LiuYang
 * @since 2025/8/14 21:59
 **/
@Service
public class FeishuTokenService {

    @Autowired
    private FeishuConfig feishuConfig;
    @Value("${feishu.api.token-url}")
    private String TOKEN_URL;

    private String cachedToken;
    private long expireTime;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    public synchronized String getTenantAccessToken() {
        if (cachedToken == null || System.currentTimeMillis() > expireTime) {
            try {
                String url = TOKEN_URL;
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                String jsonPayload = String.format(
                        "{\"app_id\":\"%s\",\"app_secret\":\"%s\"}",
                        feishuConfig.getAppId(), feishuConfig.getAppSecret()
                );

                HttpEntity<String> entity = new HttpEntity<>(jsonPayload, headers);
                ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

                if (response.getStatusCode() == HttpStatus.OK) {
                    JsonNode root = objectMapper.readTree(response.getBody());
                    int code = root.get("code").asInt();
                    if (code == 0) {
                        cachedToken = root.get("tenant_access_token").asText();
                        long expire = root.get("expire").asLong();
                        expireTime = System.currentTimeMillis() + (expire - 200) * 1000; // 提前200秒刷新
                    } else {
                        throw new RuntimeException("获取 token 失败: " + root.get("msg").asText());
                    }
                } else {
                    throw new RuntimeException("HTTP 请求失败: " + response.getStatusCodeValue());
                }
            } catch (Exception e) {
                throw new RuntimeException("获取飞书 token 异常", e);
            }
        }
        return cachedToken;
    }
}
